package com.forum.servlet;

import com.forum.bean.Topic;
import com.forum.bean.User;
import com.forum.dao.TopicDao;
import com.forum.dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by young on 2017/6/11.
 *
 * @version 1.0
 */
@WebServlet(name = "TopicListServlet", urlPatterns = "/topicList")
public class TopicListServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int currPage = 1;
        int page = 1;
        if (request.getParameter("page") != null) {
            currPage = Integer.parseInt(request.getParameter("page"));
        }

        TopicDao topicDao = new TopicDao();
        List<Topic> list = topicDao.listTopics(currPage);
        request.setAttribute("list", list);
        int count = topicDao.findCount();
        if (count % Topic.PAGE_SIZE == 0) {
            page = count / Topic.PAGE_SIZE;
        } else {
            page = count / Topic.PAGE_SIZE + 1;
        }
        StringBuffer sb = new StringBuffer();
        int i = 1;
        for (i = 1; i <= page; i++) {
            if (i == currPage) {
                sb.append("<button id='page-list'>" + i + "</button>");
            } else {
                sb.append("<a href='/topicList?page=" + i + "'><button class='page-list'>" + i + "</button></a>");
            }

        }
        request.setAttribute("bar", sb.toString());
        request.getRequestDispatcher("/topic.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}
